package com.xrit.sunnyday.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.service.MemberService;
import com.xrit.sunnyday.service.ReportService;
import com.xrit.sunnyday.service.SetmealService;
import com.xrit.sunnyday.utils.DateUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {


    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    /**
     * 会员折线图
     *
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport() {


            //1.1【对应前端页面months对应的数据】:过去12个月的每一个月的会员总量
            List<String> months = new ArrayList<>();
            //使用java的Calendar日期类来操作前端页面需要的时间
            Calendar calendar = Calendar.getInstance();
            //获取过去1年.add();
            calendar.add(Calendar.YEAR, -1);
            //获取过去1年的月份
            for (int i = 0; i < 12; i++) {
                try {
                    calendar.add(Calendar.MONTH, 1);
                    //拿到过去1年每个月的日期
                    Date date = calendar.getTime();
                    //转换日期格式->2020-06-13、2020-07-13、2020-08-13...
                    String dateString = DateUtils.parseDate2String(date);
                    //添加到月份集合
                    months.add(dateString);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //2.【对应前端页面会员数量】：过去1年的每个月会员的总量
            List<Integer> memberCount = memberService.getMemberReport(months);
            //构建总数据集合
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("months", months);
            resultMap.put("memberCount", memberCount);
            //返回Map数据
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, resultMap);
        }


    /**
     * 套餐预约占比
     */
    @GetMapping("getSetmealReport")
    public Result getSetmealReport() {
        //1.调用服务查询套餐预约占比，它包含了套餐的Name集合
          List<Map<String,Object>> setmealCount= setmealService.findSetmealCount();
        //2.抽取套餐名称集合
     List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> map : setmealCount) {//{value:2,name:"xxx"}
            String name = (String) map.get("name");
             setmealNames.add(name);
        }
        //构建总数据集合
       Map<String,Object> resultMap= new HashMap<>();
        resultMap.put("setmealNames",setmealNames);
        resultMap.put("setmealCount",setmealCount);

        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,resultMap);

    }

    /**
     * 运营统计数据
     */

    @GetMapping("getBusinessReportData")
    public Result getBusinessReportData(){
        Map<String, Object> businessReport = reportService.getBusinessReport();
        return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,businessReport);
    }
    /**
     * 导出运营统计数据报表
     */
    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest req, HttpServletResponse res){
        //1.获取所有的报表的数据
        Map<String, Object> reportData = reportService.getBusinessReport();
        //获取excel模板的路径
        String template = req.getSession().getServletContext().getRealPath("/template/report_template.xlsx");
        //jdk1.7新特性，try(流、工作簿..不用手动关流)
        try(FileInputStream fis = new FileInputStream(template);
            OutputStream os = res.getOutputStream();
            Workbook wk = new XSSFWorkbook(fis)){
            //2.获取工作表
            Sheet sht = wk.getSheetAt(0);
            //获取单元格并赋值
            //============日期===============
            sht.getRow(2).getCell(5).setCellValue(reportData.get("reportDate").toString());

            //============会员信息===============
            sht.getRow(4).getCell(5).setCellValue((Integer)reportData.get("todayNewMember"));
            sht.getRow(4).getCell(7).setCellValue((Integer)reportData.get("totalMember"));
            sht.getRow(5).getCell(5).setCellValue((Integer)reportData.get("thisWeekNewMember"));
            sht.getRow(5).getCell(7).setCellValue((Integer)reportData.get("thisMonthNewMember"));

            //============预约数量===============
            sht.getRow(7).getCell(5).setCellValue((Integer)reportData.get("todayOrderNumber"));
            sht.getRow(7).getCell(7).setCellValue((Integer)reportData.get("todayVisitsNumber"));
            sht.getRow(8).getCell(5).setCellValue((Integer)reportData.get("thisWeekOrderNumber"));
            sht.getRow(8).getCell(7).setCellValue((Integer)reportData.get("thisWeekVisitsNumber"));
            sht.getRow(9).getCell(5).setCellValue((Integer)reportData.get("thisMonthOrderNumber"));
            sht.getRow(9).getCell(7).setCellValue((Integer)reportData.get("thisMonthVisitsNumber"));

            //============热门套餐===============
            //获取热门套餐的数据
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) reportData.get("hotSetmeal");
            //先定位到模板的12行
            int rowIndex = 12;
            for (Map<String, Object> setmeal : hotSetmeal) {
                sht.getRow(rowIndex).getCell(4).setCellValue((String)setmeal.get("name"));
                sht.getRow(rowIndex).getCell(5).setCellValue((Long)setmeal.get("setmeal_count"));
                BigDecimal proportion = (BigDecimal)setmeal.get("proportion");
                sht.getRow(rowIndex).getCell(6).setCellValue(proportion.doubleValue());
                rowIndex++;
            }
            String filename = "运营统计数据报表.xlsx";
            // 解决下载的文件名 中文乱码
            filename = new String(filename.getBytes(), "ISO-8859-1");

            //3.告诉浏览器，是下载文件
            // 设置头信息，告诉浏览器，是带附件的，文件下载
            res.setHeader("Content-Disposition","attachement;filename=" + filename);
            // 设置内容体的文件格式是excel
            res.setContentType("application/vnd.ms-excel");
            //数据输出到文件
            wk.write(os);
            //刷新
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}